<template>
	<view>
		<!-- #ifdef MP-WEIXIN -->
		<camera class="camera-box" devic-position="width">
			<!-- 相机蒙层效果实现 -->
			<view class="page-flex" style="width:100%; height:100%;">
				<!-- 顶部蒙层 -->
				<view class="page-mask" style="height:45%; width:100%">
					<view class="cameraTips" style="position: absolute;top: 40%;">{{textContent}}</view>
				</view>
				<view class="cameraregion" style="height:5%;width:100%">
					<!-- 中心位置左侧蒙层 -->
					<!-- <view class="page-mask" style="height:5%;width:13%"></view> -->
					<view style="background-color: rgba(0, 0, 0, 0.7);width: 13%;" src></view>
					<image class="active-image" style="flex:1;width: 84%;" src></image>
					<view style="background-color: rgba(0, 0, 0, 0.7);width: 13%;" src></view>
					<!-- <image class="active-image" src="" style="flex: 1;"></image> -->
					<!-- 中心位置右侧蒙层 -->
					<!-- <view class="page-mask" style="height:5%;width:13%"></view> -->
				</view>
				<!-- 底部蒙层 -->
				<view class="page-mask cameraBgView" style="width:100%;height:50%;">
				</view>
				<!-- 拍照识别内容按钮 -->
				<view
					style="position: absolute;width:100%;height:150px;display: flex;justify-content: center;bottom: 10rpx;z-index: 1111;">
					<view
						style="width:100px;height:150px;display: flex;align-items: center;justify-content: center;flex-direction: column;">
						<image class="takephoto" style="" src='/static/xiangjibtn.png' @click='takePhotoAction'>
						</image>
						<view class="ttext">立即识别</view>
					</view>
				</view>
				<!-- 返回按钮 -->
				<view
					style="position: absolute;width:100px;height:150px;display: flex;align-items: center;justify-content: center;flex-direction: column;margin-left:15px;bottom:10rpx;z-index: 1111;"
					@click="cameraBlack">
					<image class="cancelphoto" src='/static/back-white.png' bindtap='actionflash' style=""></image>
				</view>
				<!-- canvas-id="image-canvas" -->
				<!-- <canvas wx:if='{{isShowImage}}' id="image-canvas" type="2d"
					style='position: absolute; height: 5%;top: 20%;background-color: aqua;width: 84%;margin-left: 13%;'></canvas> -->
				<canvas canvas-id="image-canvas" v-if='isShowImage' style='position: absolute; height: 5%;top: 45%;background-color: aqua;width: 84%;margin-left: 13%;'></canvas>
			</view>
		</camera>

		<!-- #endIf -->
	</view>

</template>

<script>
	let _this = null;
	export default {
		data() {
			return {
				src: "",
				session: '',
				frameBuffer: '',
				width: '',
				height: '',

				isShowCamera: true,
				isShowImage: false,
				textContent: '可以扫描前挡风，行驶证，车辆铭牌车架号',
				canvasWidth: '', //系统屏幕的宽度
				canvasHeight: '', //系统屏幕的高度
				imgInfo: {},

				ctx: {},
				imageDatabuffer: {}
			}
		},
		onLoad() {
			// #ifdef MP-WEIXIN
			var that = this
			// 获取系统信息，设置canvas宽高
			uni.getSystemInfo({
				success(res) {
					that.canvasWidth = res.windowWidth
					that.canvasHeight = res.windowHeight
					console.log("打印系统宽度  this.canvasWidth   " + JSON.stringify(that.canvasWidth))
					console.log("打印系统高度度  that.canvasHeight   " + JSON.stringify(that.canvasHeight))
				}
			})
			// #endIf
		},
		methods: {

			// 点击扫证，可拍照、可选择本机图片
			getImage() {
				var that = this
				wx.showActionSheet({
					itemList: ['拍照', '相册'],
					success(res) {
						let index = res.tabIndex;
						if (index == 0) {
							// that.gotophoto();
						} else {
							that.getAlbum();
						}
					}
				})
			},
			//从相册选择图片
			getAlbum() {
				const that = this
				uni.chooseImage({
					count: 1,
					sourceType: ['album'],
					success: function(res) {
						var path = res.tempFilePaths[0];
						that.$utils.log("从相册选择图片 success " + JSON.stringify(res))
						// that.getBase64Path(path).then(base64 => {
						// 	that.$utils.log("从getBase64Path  success " + JSON.stringify(base64))
						// 	that.ocrCard(base64).then(res => {
						// 		that.$utils.log("从base64  success " + JSON.stringify(res))
						// 		//这里就是扫描的结果
						// 		console.log(res);
						// 	})
						// });
						that.getBase64Path(path)
					}
				})
			},
			//本地转化为base64编码
			getBase64Path(path) {
				const that = this
				wx.getFileSystemManager().readFile({
					filePath: path,
					encoding: 'base64',
					success: function(res) {
						// that.$utils.log("本地转化为base64编码 getBase64Path   " + JSON.stringify(res))
						// resolve(res.data);
						that.ocrCard(res.data)
					},
					fail: function(error) {
						that.$utils.log("本地转化为base64编码 getBase64Path  error  " + JSON.stringify(error))
						reject(error)
					}
				})
			},

			//获取access_token
			getToken() {
				const that = this
				return new Promise((resolve, reject) => {
					let appKey = 'rYjdj5eopihyUanxWi53ZkSL';
					let secretKey = 'IBGNwoTg4zanGyVuH4N1dXIh2OeMVCgS';
					let url =
						`https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=${appKey}&client_secret=${secretKey}`;
					uni.request({
						url: url,
						method: 'POST',
						dataType: 'json',
						header: {
							'content-type': 'application/json; charset-UTF-8'
						},
						success(res) {
							that.$utils.log("getToken  resolve" + JSON.stringify(res))
							resolve(res);
						},
						fail(err) {
							that.$utils.log("getToken  resolve" + JSON.stringify(err))
							reject(err);
						}
					})
				})
			},

			//识别图片
			ocrCard(data) {
				const that = this
				this.getToken().then(res => {
					var token = res.data.access_token
					var url = 'https://aip.baidubce.com/rest/2.0/ocr/v1/vin_code?access_token=' + token
					that.$utils.log("打印 识别vin图片的时候的 url====  " + JSON.stringify(url))
					uni.request({
						url: url,
						method: 'POST',
						header: {
							'Content-Type': 'application/x-www-form-urlencoded'
						},
						data: {
							image: data
						},
						success(res) {
							that.$utils.log("ocrCard 识别图片 resolve" + JSON.stringify(res))
							// uni.showModal({
							// 	content:' OCR 识别   ' + JSON.stringify(res.data)
							// })
							if(res.statusCode == '200'){
								if(res.data.words_result){
									that.BackhaulOBJ(res.data.words_result[0])
								}else{
									uni.showToast({
										title:'识别失败，请重新拍照识别！',
										icon:'none',
										duration:1000
									})
								}
							}else{
								uni.showToast({
									title:'识别失败，请重新拍照识别！',
									icon:'none',
									duration:1000
								})
							}
							// resolve(res);
						},
						fail(err) {
							uni.showToast({
								title:'识别失败，请联系客服进行反馈！',
								icon:'none',
								duration:1000
							})
							that.$utils.log("ocrCard 识别图片 err " + JSON.stringify(err))
							// reject(err);
						}
					})
				})
			},
			
			BackhaulOBJ(obj){
				this.$utils.log('打印点击的item   ' + JSON.stringify(obj))
				// 获取当前页上的栈（数组形式）
				var pages = getCurrentPages()
				//上一页面 
				var prevPage = pages[pages.length - 2]
				obj.IsVIN = true
				prevPage.$vm.backData(obj) /// backData为A页面定义好的一个方法 调用该方法obj数据会返回到A页面backData方法中
				// 返回上一页
				uni.navigateBack()
			},
			

			//js
			takePhotoAction() {
				var that = this;
				let ctx = wx.createCameraContext();
				ctx.takePhoto({
					quality: 'high',
					success(res) {
						that.src = res.tempImagePath
						// 获取图片信息
						wx.getImageInfo({
							src: that.src,
							success(imageRes) {
								that.imgInfo = imageRes
								console.log("打印获取拍照的到的图片资源的 相关信息  " + JSON.stringify(that.imgInfo))
								that.makeCanvas()
							}
						})

					}
				})
			},
			// init(ctx, canvas) {
			// 	var that = this
			// 	let img = canvas.createImage()
			// 	img.src = this.imgInfo.path;
			// 	img.onload = (e) => {
			// 		//截取图片指定部分并绘制到canvas
			// 		ctx.drawImage(img, this.imgInfo.width * 13 / 100, this.imgInfo.height * 45 /
			// 			100, this
			// 			.imgInfo.width * 84 / 100, this.imgInfo.height * 5 / 100, 0, 0, this.canvasWidth * 84 /
			// 			100, this
			// 			.canvasHeight * 5 / 100) //width固定为300,按比例计算出height
			// 		ctx.draw()
			// 		//将canvas内容保存为图片
			// 		wx.canvasToTempFilePath({
			// 			canvas: canvas,
			// 			// x: 50, //画布x轴起点
			// 			// y: 280, //画布y轴起点
			// 			width: that.imgInfo.width * 84 / 100, //画布宽度
			// 			height: that.imgInfo.height * 5 / 100, //画布高度
			// 			// destWidth: 335, //输出图片宽度
			// 			// destHeight: 216, //输出图片高度
			// 			fileType: 'png',
			// 			success: (res) => {
			// 				console.log("canvasToTempFilePath   111111  " + JSON.stringify(res))

			// 				//将图片保存到本地相册
			// 				// wx.saveImageToPhotosAlbum({
			// 				// 	filePath: res.tempFilePath,
			// 				// })
			// 			},
			// 			fail: (res) => {
			// 				console.log(res)
			// 			}
			// 		})
			// 	}
			// 	img.onerror = (e) => {
			// 		console.error('err:', e)
			// 	}
			// },

			// takePhoto() {
			// 	var that = this
			// 	const ctx = uni.createCameraContext();
			// 	ctx.takePhoto({
			// 		quality: 'high',
			// 		success: (res) => {
			// 			that.src = res.tempImagePath
			// 			// 获取图片信息
			// 			wx.getImageInfo({
			// 				src: that.src,
			// 				success(imageRes) {
			// 					that.imgInfo = imageRes
			// 					console.log("打印获取拍照的到的图片资源的 相关信息  " + JSON.stringify(that
			// 						.imgInfo))
			// 					// 制作画布
			// 					that.makeCanvas();
			// 				}
			// 			})

			// 			that.$utils.log("打印拍照返回的数据" + JSON.stringify(res))
			// 		}
			// 	});
			// },

			makeCanvas() {
				// #ifdef MP-WEIXIN
				this.$utils.log("进入makeCanvas  方法")
				// let cWidth = this.imgInfo.width * 84 / 100;
				// let cHeight = this.imgInfo.height * 5 / 100;
				this.isShowImage = true
				var that = this
				const canvasCtx = this.canvasCtx = wx.createCanvasContext('image-canvas')
				// 设置背景
				canvasCtx.setFillStyle('#ffffff')
				let cWidth = this.imgInfo.width * 84 / 100;
				let cHeight = this.imgInfo.height * 5 / 100;
				canvasCtx.fillRect(0, 0, this.canvasWidth * 84 / 100, cHeight)
				// canvas宽高

				this.$utils.log("进入makeCanvas  方法 canvas宽高  cWidth" + cWidth)
				this.$utils.log("进入makeCanvas  方法 canvas宽高 cHeight " + cHeight)
				this.$utils.log("进入makeCanvas  this.imgInfo.path " + this.imgInfo.path)
				// 描绘图片

				// ctx.drawImage(this.imgInfo.path,this.imgInfo.width * 13 / 100 * this.imgInfo.width / this.canvasWidth, this.imgInfo.height * 45 / 100 * this.imgInfo.height / this.canvasHeight, this.imgInfo.width * 84 / 100 * this.imgInfo.width / this.canvasWidth, this.imgInfo.height * 5 / 100 * this.imgInfo.height / this.canvasHeight, 0, 0, this.imgInfo.width * 84 / 100 * this.imgInfo.width / this.canvasWidth, this.imgInfo.height * 5 / 100 * this.imgInfo.height / this.canvasHeight)
				canvasCtx.drawImage(this.imgInfo.path, this.imgInfo.width * 13 / 100, this.imgInfo.height * 45 /
					100, cWidth, cHeight, 0, 0, this.canvasWidth * 84 / 100, this.canvasHeight * 5 / 100)
				// this.drawImage(ctx, this.imgInfo.path, this.imgInfo.width, this.imgInfo.height, cWidth, cHeight);

				canvasCtx.draw(false, setTimeout(() => {
					//回调方法
					console.log("画布内容已经画完  执行转化 的方法")
					//将canvas内容保存为图片
					wx.canvasToTempFilePath({
						// canvas: canvasCtx,
						// x: 50, //画布x轴起点
						// y: 280, //画布y轴起点
						width: that.imgInfo.width * 84 / 100, //画布宽度
						height: that.imgInfo.height * 5 / 100, //画布高度
						// destWidth: 335, //输出图片宽度
						// destHeight: 216, //输出图片高度
						fileType: 'png',
						canvasId: 'image-canvas',
						success: (res) => {
							console.log("canvasToTempFilePath   111111  " + JSON.stringify(res))
							that.getBase64Path(res.tempFilePath)
							//将图片保存到本地相册
							// wx.saveImageToPhotosAlbum({
							// 	filePath: res.tempFilePath,
							// })
						},
						fail: (res) => {
							console.log(res)
						}
					})
				}, 500))

				// #endIf
			},

			error(e) {
				console.log(e.detail);
			},

			cameraBlack() {
				uni.navigateBack()
			}
		}
	}
</script>

<style lang="less">
	page {
		width: 100%;
		height: 100%;
		/* background-color: #fff; */
		overflow: hidden;
	}

	.camera-box {
		width: 100vw;
		height: 100vh;
	}

	/*  形成遮罩  */
	.page-mask {
		background-color: rgba(0, 0, 0, 0.7);
	}

	.cameraTips {
		width: 100%;
		text-align: center;
		font-size: 14px;
		color: #FFF;
	}

	.cameraregion {
		display: flex;
	}

	.ttext {
		font-size: 28rpx;
		margin-top: 12rpx;
		color: #fff;
		font-weight: bold;
		margin-top: 10px;
		/* z-index: 999; */
	}

	/* 背景图像view */
	.camerabgImage-view {
		height: 100%;
		width: 100%;
		position: absolute;
		z-index: 999;
	}

	/* 提示文本2 */
	.cameraTips2 {
		margin-top: 22%;
		text-align: center;
		color: #fff;
	}

	.cameraactive {
		margin-top: 12px;
		position: absolute;
		width: 100%;
		display: flex;
		justify-content: center;
	}

	.active-image {
		display: block;
		width: 350px;
		height: 90rpx;
	}

	/* 拍照背景view */
	.cameraBgView {
		position: relative;
		display: flex;
	}

	/* 按钮view*/
	.cameraButton-view {
		height: 200rpx;
		width: 100%;
		position: absolute;
		display: flex;
		justify-content: space-around;
	}

	/* 取消按钮 */
	.cancelphoto {
		width: 50rpx;
		height: 50rpx;
	}

	/* 拍照按钮 */
	.takephoto {
		border-radius: 999px;
		box-shadow: 0 0 50rpx #ffd8a2;
		width: 152rpx;
		height: 152rpx;
	}
</style>